package com.video4s.parser;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;




public class Vimeo {

	
	
	
	private String[] getTitleAndDescription(String url) {
		
		String[] str = new String[2];
		try {
			Document doc = Jsoup.connect(url).userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31").get();
			Elements els = doc.select("meta[name=description]");
			str[0] = new String(doc.title().trim());
			str[1] = new String(els.attr("content").trim());
		} catch (Exception e) {
			str[0] = new String();
			str[1] = new String();
		}
		
		return str;
	}
	
	public void getMoreVideo(String url)  {
		try {
			if(!url.equals("http://vimeo.com"))  {
				Document doc = Jsoup.connect(url).userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31").get();
				Elements els;
				if(doc.select("a[href~=^(/\\d+)$]:has(img)").text().equals("")) {
					 els = doc.select("a[href~=^/(channels|groups)/\\w+(/videos)?(/\\d+)$]:has(img)");
				} else {
					 els = doc.select("a[href~=^(/\\d+)$]:has(img)");
				}
				String linkPage = "http://vimeo.com";
				try {
					Elements elsPagination = doc.select("div#pagination.pagination ol li a.selected");
					String pageCurrent = elsPagination.attr("data-page").trim();
					int page = Integer.parseInt(pageCurrent) + 1;
					System.out.println(page);
					linkPage =  linkPage+elsPagination.attr("href").toString().replace("page:"+pageCurrent, ("page:"+page));
					System.out.println(linkPage);
				} catch (Exception e) {
					// TODO: handle exception
				}
				getListChilrent(els);
			    getMoreVideo(linkPage);
			    
			}
		} catch (Exception e) {
			System.out.println("Error Get More: "+e.getMessage());
		}
	}
	
	public void getListChilrent(Elements els) throws Exception {
		for (Element element : els) {
			String link;
			Pattern replace = Pattern.compile("^/(channels|groups)/\\w+(/videos)?(/\\d+)$");
		    Matcher matcher = replace.matcher(element.attr("href"));
			if(matcher.matches()) {
				link = "http://vimeo.com"+matcher.group(3);
			} else {
				link = "http://vimeo.com"+element.attr("href");
			}
			
			String img = element.select("img").attr("src");
			//String title = element.select("p.title").text();
			String[] titleDesctiption = getTitleAndDescription(link);
			System.out.println("Link:" + link);
			System.out.println("Image:" + img);
			System.out.println("Title:" + titleDesctiption[0]);
			System.out.println("Description:" + titleDesctiption[1]);
			
		}
		
	}
	public void getListYou(String url) throws Exception {
			Document doc = Jsoup.connect(url).userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31").get();
			Elements els;
			if(doc.select("a[href~=^(/\\d+)$]:has(img)").text().equals("")) {
				 els = doc.select("a[href~=^/(channels|groups)/\\w+(/videos)?(/\\d+)$]:has(img)");
			} else {
				 els = doc.select("a[href~=^(/\\d+)$]:has(img)");
			}
			String linkPage = "http://vimeo.com";
			try {
				Elements elsPagination = doc.select("div#pagination.pagination ol li a.selected");
				String pageCurrent = elsPagination.attr("data-page").trim();
				int page = Integer.parseInt(pageCurrent) + 1;
				System.out.println(page);
				linkPage =  linkPage+elsPagination.attr("href").toString().replace("page:"+pageCurrent, ("page:"+page));
				System.out.println(linkPage);
			} catch (Exception e) {
				// TODO: handle exception
			}
			
			for (Element element : els) {
				String link;
				Pattern replace = Pattern.compile("^/(channels|groups)/\\w+(/videos)?(/\\d+)$");
			    Matcher matcher = replace.matcher(element.attr("href"));
				if(matcher.matches()) {
					link = "http://vimeo.com"+matcher.group(3);
				} else {
					link = "http://vimeo.com"+element.attr("href");
				}
				
				String img = element.select("img").attr("src");
				//String title = element.select("p.title").text();
				String[] titleDesctiption = getTitleAndDescription(link);
				System.out.println("Link:" + link);
				System.out.println("Image:" + img);
				System.out.println("Title:" + titleDesctiption[0]);
				System.out.println("Description:" + titleDesctiption[1]);
				
			}
			getMoreVideo(linkPage);
		
	}
	
	
	public void getFileVideo(String id,String userAgent) throws Exception {
		Document doc = Jsoup.connect("http://player.vimeo.com/video/"+id).userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31").get();
		Elements els = doc.select("script");
		Element elses = els.get(1);
		String a = elses.toString();
		String timestamp = a.substring(a.lastIndexOf("timestamp")+"timestamp\":".length(),a.lastIndexOf("signature")-",\"".length());
		String sessionId = a.substring(a.lastIndexOf("signature")+"signature\":\"".length(),a.lastIndexOf("referrer")-"\",\"".length());
		System.out.println(timestamp);
		System.out.println(sessionId);
		
		
		String link = "http://player.vimeo.com/play_redirect?clip_id="+id+"&sig="+sessionId+"&time="+timestamp+"&quality=hd&codecs=H264,VP8,VP6&type=moogaloop&embed_location=&seek=0";
		
		URL obj = new URL(link);
		HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
		conn.setDoOutput(true); 
		conn.setInstanceFollowRedirects(false); 
		conn.setRequestMethod("GET"); 
		conn.setReadTimeout(5000);
		conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
		conn.addRequestProperty("Connection", "en-US,en;q=0.8");
		conn.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31");
	
		System.out.println("Request URL ... " + link);
	 
		boolean redirect = false;
	 
		// normally, 3xx is redirect
		int status = conn.getResponseCode();
		if (status != HttpURLConnection.HTTP_OK) {
			if (status == HttpURLConnection.HTTP_MOVED_TEMP
				|| status == HttpURLConnection.HTTP_MOVED_PERM
					|| status == HttpURLConnection.HTTP_SEE_OTHER)
			redirect = true;
		}
	 
		System.out.println("Response Code ... " + status);
	 
		if (redirect) {
	 
			// get redirect url from "location" header field
			String newUrl = conn.getHeaderField("Location");
	 
			// get the cookie if need, for login
			//String cookies = conn.getHeaderField("Set-Cookie");
			
			// open the new connnection again
			//conn = (HttpURLConnection) new URL(newUrl).openConnection();
			//conn.setRequestProperty("Cookie", cookies);
			//conn.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31");
			System.out.println("Redirect to URL : " + newUrl);
	 
		}
	 
		

		
	}
	public static void main(String[] args) throws Exception {

		//new VimeoLoad().threadQueue();
		new Vimeo().getFileVideo("2108952","111");
		//new VimeoLoad().getListYou("http://vimeo.com/categories/films/videos/");
		//new VimeoLoad().getMoreVideo("http://vimeo.com/categories/films/videos/page:10/sort:relevant");
		

	}

}
